<template lang="pug">
.login
  .login-logo
    img(src="../../static/images/logo.png")
  .login-container
    el-form.login-form(
      v-if="isLogin"
      :model="loginForm"
      :rules="loginRules"
      ref="loginForm"
      label-width="0"
    )
      el-form-item(prop="userName")
        el-input(v-model="loginForm.userName" autocomplete="new-password" placeholder="请输入用户名称")
          i.el-input__icon.el-icon-user-solid(slot="prefix")
      el-form-item(prop="password")
        el-input(type="password" v-model="loginForm.password" autocomplete="new-password" placeholder="请输入登录密码")
          i.el-input__icon.icon-lock(slot="prefix")
      .form-checkboxs
        el-checkbox(v-model="checked" true-label="1" false-label="0") 记住密码
        el-checkbox(v-model="avoid" true-label="1" false-label="0") 15天免登录
      .login-form-btn
        el-button(@click="login" type="primary") 确定
      .login-form-footer
        span(@click="reset") 重置密码
        .register(@click="showReister") 还没账号？快注册吧>
    el-form.login-form(
      v-if="isReset"
      :model="resetForm"
      :rules="resetRules"
      ref="resetForm"
      label-width="0"
    )
      el-form-item(prop="mobile")
        el-input(v-model="resetForm.mobile" autocomplete="new-password" clearable placeholder="请输入手机号码")
          i.el-input__icon.icon-phone(slot="prefix")
      el-form-item(prop="msgCode")
        el-input(v-model="resetForm.msgCode" autocomplete="new-password" placeholder="请输入验证码")
          i.el-input__icon.icon-code(slot="prefix")
          .form-item-suffix(slot="suffix", :class="time && 'disabled'" @click="sendCode") {{time ? '重发验证码'+ time : '获取验证码'}}
      el-form-item(prop="password")
        el-input(type="password" v-model="resetForm.password" autocomplete="new-password" placeholder="请输入密码")
          i.el-input__icon.icon-lock(slot="prefix")
      el-form-item(prop="passwordReset")
        el-input(type="password" v-model="resetForm.passwordReset" autocomplete="new-password" placeholder="请重新输入密码")
          i.el-input__icon.icon-lock(slot="prefix")
      .login-form-btn
        el-button(@click="confirmReset" type="primary") 重置密码
      .login-form-footer
        .register(@click="showLogin") 已有账户？立即登录>
    el-form.login-form(
      v-if="isRegister"
      :model="registerForm"
      :rules="registerRules"
      ref="registerForm"
      label-width="0"
    )
      el-form-item(prop="userName")
        el-input(v-model="registerForm.userName" placeholder="请输入用户名称" autocomplete="new-password")
          i.el-input__icon.el-icon-user-solid(slot="prefix")
      el-form-item(prop="mobile")
        el-input(v-model="registerForm.mobile" autocomplete="new-password" clearable placeholder="请输入手机号码")
          i.el-input__icon.icon-phone(slot="prefix")
      el-form-item(prop="msgCode")
        el-input(v-model="registerForm.msgCode" autocomplete="new-password" placeholder="请输入验证码")
          i.el-input__icon.icon-code(slot="prefix")
          .form-item-suffix(slot="suffix", :class="time && 'disabled'" @click="sendRegisterCode") {{time ? '重发验证码'+ time : '获取验证码'}}
      el-form-item(prop="password")
        el-input(type="password" v-model="registerForm.password" autocomplete="new-password" placeholder="请输入密码")
          i.el-input__icon.icon-lock(slot="prefix")
      el-form-item(prop="passwordRegister")
        el-input(type="password" v-model="registerForm.passwordRegister" autocomplete="new-password" placeholder="请重新输入密码")
          i.el-input__icon.icon-lock(slot="prefix")
      el-form-item(prop="companyName")
        el-input(v-model="registerForm.companyName" placeholder="请输入公司名称")
          i.el-input__icon.icon-company(slot="prefix")
      el-form-item(prop="styles")
        el-select(v-model="registerForm.styles" multiple placeholder="请选择类型")
          el-option(v-for="item in styles", :label="item.styleName", :value="item.styleId")
      el-form-item(prop="mainBusiness")
        el-select(v-model="registerForm.mainBusiness" multiple placeholder="请选择主营业务")
          el-option(v-for="item in firstCategory", :label="item.name", :value="item.id")
      .login-form-btn
        el-button(@click="confirmRegister" type="primary") 注册
      .login-form-footer
        .register(@click="showLogin") 已有账户？立即登录>
</template>

<script>
const warning = {
  accout: '帐号必填',
  pswd: '密码必填',
  imgCode: '验证码必填',
  mobile: '手机号必填',
  code: '短信验证码必填',
  newPswd: '新密码必填',
  repeatPswd: '再次输入新密码必填'
}
let timer = null
import { hex_md5_salt } from 'utils/md5'
import { base64decode, base64encode } from 'utils/base64'
import { setCookie } from 'utils/cookie'
import { login, getUserInfo, toResetPassword, toSendMsg, getStyles, toRegister, getFirstCategory } from 'api'
import { mapActions } from 'vuex'
export default {
  name: 'login',
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.resetForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validatePass3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        userName: '',
        password: '',
        // imgCode: ''
      },
      loginRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 20, message: '用户名不能大于20位中文、字母、数字、下划线', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      resetForm: {
        mobile: '',
        password: '',
        passwordReset: '',
        msgCode: ''
      },
      resetRules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/, message: '手机号格式错误', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        passwordReset: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        msgCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      registerForm: {
        companyName: '',
        password: '',
        passwordRegister: '',
        mobile: '',
        msgCode: '',
        userName: '',
        styles: [],
        mainBusiness: []
      },
      registerRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 20, message: '用户名不能大于20位中文、字母、数字、下划线', trigger: 'blur' }
        ],
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/, message: '手机号格式错误', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        passwordRegister: [
          { validator: validatePass3, trigger: 'blur' }
        ],
        msgCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        styles: [
          { type: 'array', required: true, message: '请选择类型', trigger: 'change' }
        ],
        mainBusiness: [
          { type: 'array', required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      styles: [],
      firstCategory: [],
      checked: '0',
      avoid: '0',
      isLogin: true,
      isReset: false,
      isRegister: false,
      time: 0
    }
  },
  computed: {},
  methods: {
    ...mapActions([
      'changeUserInfo'
    ]),
    async login () {
      this.$refs.loginForm.validate(async (valid) => {
        try {
          if (valid) {
            this.loading = true
            const { ResultSet } = await this.$axios.post(login, {content: { ...this.loginForm, password: hex_md5_salt(encodeURIComponent(this.loginForm.password)), isLogin: true }})
            if (this.avoid) localStorage.setItem('isAvoid', this.avoid)
            if (this.checked) this.setStorage(this.loginForm.userName, base64encode(this.loginForm.password))
            else this.clearStorage()
            setCookie('COMPANY_NAME', ResultSet.userData.companyName, '/', this.avoid ? 15 : 7);
            setCookie('CNPASS_PLAT', escape(ResultSet.userData.token), '/', this.avoid ? 15 : 7);
            setCookie('HEADIMG', ResultSet.userData.headImage, '/', this.avoid ? 15 : 7);
            setCookie('CNPASS', ResultSet.userData.token, this.avoid ? 15 : 7)
            this.loading = false
            this.$router.replace({name: 'index'})
          }
        } catch(err) {
          console.log(err)
          this.loading = false
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    async getUserInfo () {
      try {
        const { ResultSet } = await this.$axios.post(getUserInfo)
        this.changeUserInfo(ResultSet.userData)
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    reset () {
      this.time = 0
      this.isLogin = false
      this.isReset = true
      this.isRegister = false
    },
    setStorage (c_name, c_pwd) {
      localStorage.setItem('isRemember', this.checked)
      localStorage.setItem('userName', c_name)
      localStorage.setItem('userPwd', c_pwd)
    },
    //清除cookie
    clearStorage () {
      localStorage.removeItem('isRemember')
      localStorage.removeItem('userName')
      localStorage.removeItem('userPwd')
    },
    showLogin () {
      this.time = 0
      this.isLogin = true
      this.isReset = false
      this.isRegister = false
    },
    codeTimer () {
      this.time = 60
      timer = setInterval(() => {
        this.time--
        if (this.time <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    async sendCode () {
      try {
        let reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
        if (this.time > 0 && !this.isSendCode) {
          return
        }
        if (!this.resetForm.mobile || !reg.test(this.resetForm.mobile)) {
          this.$message.error('请输入正确的手机号！')
          return
        }
        this.isSendCode = true
        await this.$axios.post(toSendMsg, { content: { mobile: this.resetForm.mobile, isReset: true } })
        this.isSendCode = false
        this.codeTimer()
        this.$message.success('短信验证码已发送')
      } catch (err) {
        this.isSendCode = false
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async confirmReset () {
      this.$refs.resetForm.validate(async valid => {
        try {
          if (valid) {
            await this.$axios.post(toResetPassword, { content: { ...this.resetForm, password: hex_md5_salt(encodeURIComponent(this.resetForm.password)), passwordReset: hex_md5_salt(encodeURIComponent(this.resetForm.passwordReset)) } })
            this.$message.success('密码重置成功！')
            this.time = 0
            this.isLogin = true
            this.isReset = false
            this.isRegister = false
          }
        } catch (err) {
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    showReister () {
      this.time = 0
      this.isLogin = false
      this.isReset = false
      this.isRegister = true
    },
    async sendRegisterCode () {
      try {
        let reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
        if (this.time > 0) {
          return
        }
        if (!this.registerForm.mobile || !reg.test(this.registerForm.mobile)) {
          this.$message.error('请输入正确的手机号！')
          return
        }
        await this.$axios.post(toSendMsg, { content: { mobile: this.registerForm.mobile } })
        this.codeTimer()
        this.$message.success('短信验证码已发送')
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    confirmRegister () {
      this.$refs.registerForm.validate(async valid => {
        try {
          if (valid) {
            let query = { ...this.registerForm }
            query.password = hex_md5_salt(encodeURIComponent(query.password))
            query.passwordRegister = hex_md5_salt(encodeURIComponent(query.passwordRegister))
            query.mainBusiness = query.mainBusiness.join(',')
            query.styles = query.styles.join(',')
            await this.$axios.post(toRegister, { content: { ...query } })
            this.$message.success('恭喜，您已注册成功！')
            setTimeout(() => {
              this.time = 0
              this.isLogin = true
              this.isReset = false
              this.isRegister = false
            }, 1000)
          }
        } catch (err) {
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    async getStyles () {
      try {
        const { ResultSet } = await this.$axios.post(getStyles)
        this.styles = ResultSet.userData.businessStyles
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getFirstCategory () {
      try {
        const { ResultSet } = await this.$axios.post(getFirstCategory)
        this.firstCategory = ResultSet.userData.firstCategory
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getStyles()
      vm.getFirstCategory()
      const isRemember = localStorage.getItem('isRemember')
      const isAvoid = localStorage.getItem('isAvoid')
      vm.checked = isRemember ? isRemember : '0'
      vm.avoid = isAvoid ? isAvoid : '0'
      if (vm.checked) {
        const userName = localStorage.getItem('userName')
        const userPwd = localStorage.getItem('userPwd')
        vm.loginForm.userName = userName
        if (userPwd) {
          vm.loginForm.password = base64decode(userPwd)
        } else {
          vm.loginForm.password = ''
        }
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  position: relative;
  background-image: url(../../static/images/login_bd_1.jpg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.login-logo {
  position: absolute;
  top: 61px;
  left: 260px;
}
.login-container {
  width: 400px;
  background: #FFFFFF;
  box-shadow: 0px 1px 31px 1px rgba(89, 76, 49, 0.24);
  border-radius: 8px;
  position: absolute;
  top: 50%;
  right: 320px;
  transform: translateY(-50%);
  padding: 60px;
}
.form-item {
  margin-bottom: 24px;
}
.form-checkboxs {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-checkbox {
    color: #909090;
  }
}
.login-form {
  .el-select {
    width: 100%;
  }
}
.login-form-btn {
  width: 100%;
  margin-top: 32px;
  .el-button {
    width: 100%;
  }
}
.login-form-footer {
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #636363;
  span {
    cursor: pointer;
  }
}
.form-item-suffix {
  line-height: 40px;
  padding-right: 10px;
  color: #EB454A;
  cursor: pointer;
  &.disabled {
    color: #999;
  }
}
.register {
  cursor: pointer;
}
// .login-title {
//   text-align: center;
//   color: #bf1a21;
//   margin-bottom: 18px;
//   font-size: 26px;
// }
// .login-form {
//   width: 500px;
//   min-height: 280px;
//   background: #fff;
//   border-radius: 5px;
//   padding: 30px 50px;
// }
// .login-form-item {
//   display: flex;
//   align-items: center;
//   justify-content: space-between;
// }

// .login-form-register {
//   margin-top: 30px;
// }
</style>
